#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back

using namespace std;

typedef pair < int , int > pii;
typedef vector < int > vec;
typedef vector < pii > veg;
typedef long long ll;
typedef double db;

int read() {
    int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch =='-',ch = getchar();
    while(isdigit(ch)) x = x * 10 + (ch ^ 48),ch = getchar(); return f ? -x : x;
}

const int N = 2e5 + 10;
const int mod = 10000;

int a[N],m,n,pro[N],nxt[N];

int upd(int x) { return x + (x >> 31 & mod); }

int main() {
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
#endif
    m = in;
    for(int T = in;T;T--) {
	n = in;
	for(int i = 1;i <= n;i++) a[i] = in;
	nxt[1] = 0; pro[1] = m % mod;
	for(int i = 2,j = 0;i <= n;i++) {
		while(j && a[i] != a[j + 1]) j = nxt[j];
		if(a[j + 1] == a[i]) j++;
		nxt[i] = j; pro[i] = 1ll * pro[i - 1] * m % mod;
	}
	int ans = 0;
	for(int i = n;i;i = nxt[i]) ans = upd(ans + pro[i] - mod);
	printf("%04d\n",ans);
    } return 0;
}
